package api

import (
	"gitee.com/ling1314/origin-utility/constant"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/service"
	"github.com/gin-gonic/gin"
)

type deviceApi struct{}

func (api deviceApi) GetListByOrgId(c *gin.Context) {
	var argus = struct {
		Id int64 `uri:"id,string"`
	}{}
	if err := c.ShouldBindUri(&argus); err != nil {
		BadWithError(c, err)
		return
	}
	re, err := service.DeviceService.GetListByOrgId(argus.Id)
	if err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, re)
}

func (api deviceApi) SendInstruct(c *gin.Context) {
	var argus = struct {
		DeviceId int64       `json:"deviceId,string" form:"deviceId"`
		Code     int         `json:"code" form:"code"`
		Body     interface{} `json:"body" form:"body"`
	}{}
	if err := c.ShouldBindJSON(&argus); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	err := service.DeviceService.SendInstruct(argus.DeviceId, argus.Code, argus.Body)
	if err != nil {
		BadWithCode(c, constant.ErrorUnknown)
		return
	}
	Ok204(c)
}

func (api deviceApi) Page(c *gin.Context) {
	var item model.SearchDevice
	if err := c.ShouldBindQuery(&item); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	result, err := service.DeviceService.Page(item)
	if err != nil {
		BadWithCode(c, constant.ErrorUnknown)
		return
	}
	Ok(c, result)
}

func (api deviceApi) Detail(c *gin.Context) {
	var argus = struct {
		Id       int64  `form:"id"`
		InfoType string `form:"infoType"`
	}{}
	if err := c.ShouldBindQuery(&argus); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	result, err := service.DeviceService.Detail(argus.Id, argus.InfoType)
	if err != nil {
		if err.Error() == "id not exist" {
			BadWithCode(c, constant.DeviceIDNotExist)
			return
		}
		BadWithCode(c, constant.ErrorUnknown)
		return
	}
	Ok(c, result)
}

func (api deviceApi) GetLog(c *gin.Context) {
	argus := struct {
		LogType  string `form:"logType"`
		DeviceId int64  `form:"deviceId,string"`
	}{}
	if err := c.ShouldBindQuery(&argus); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	r, err := service.DeviceService.SelectLastLog(argus.LogType, argus.DeviceId)
	if err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, r)
}
